import React from 'react'
// 引入编辑器组件
import BraftEditor from 'braft-editor'
import { ContentUtils } from 'braft-utils'
import { CameraOutlined } from '@ant-design/icons'
// 引入编辑器样式
import 'braft-editor/dist/index.css'

import './index.less'
import FileUpload from '@/components/Upload'

export default class EditorDemo extends React.Component {

  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(this.props.content ?? null)
  }

  handleEditorChange = (editorState) => {
    // 更新编辑器的状态
    this.setState({ editorState })
    //要判断输入的内容 如果有内容，设置输入的内容 设置成空的字符串''
    let content = ''
    if (!editorState.isEmpty()) {
      content = editorState.toHTML()
    }
    this.props.name !== undefined ? this.props.name : ''
    //调用父组件的方法 将副文本传递的内容传递回去
    this.props.setDetails(content, this.props.name)
  }
  onChangeUrl = url => {
    this.setState({
      editorState: ContentUtils.insertMedias(this.state.editorState, [{
        type: 'IMAGE',
        url
      }])
    })
  }

  render () {
    const extendControls = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <FileUpload
            onHandle={this.onChangeUrl}
            accept="image/*"
            listType={'picture'}
          >
            <button type="button" className="control-item button upload-button" data-title="插入图片">
              <CameraOutlined/>
            </button>
          </FileUpload>
        )
      }
    ]
    const { editorState } = this.state
    return (
      <div className="my-component">
        <BraftEditor
          value={editorState}
          onChange={this.handleEditorChange}
          extendControls={extendControls}
        />
      </div>
    )
  }
}
